package com.testDemo.utils;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.testDemo.enrty.Bizkey;
import com.testDemo.enrty.Method;

/**
 * 生成TF_B_METHOD_BIZKEY表的数据
 * @author AllenWang
 */
public class GetBizkeyUtils {

    private static List<Bizkey> bizkeys = null;
    private static String exception = "";

    static {
        try {
            String bizkeyPath = getBizkeyExcelPath(TestUtils.bizKeyExcel);
            bizkeys = getAllBizkey(bizkeyPath);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        // 生成TF_B_METHOD_BIZKEY表的数据
        List<String> filePaths = TestUtils.getExcelFilePath(TestUtils.INTERFACE_EXCEL_PATH);
        List<String> exception = new ArrayList<String>();
        String sql = "";
        for (String methodName : filePaths) {
            methodName = methodName.substring(methodName.lastIndexOf("/") + 1, methodName.indexOf(".xlsx"));
            methodName = methodName.replaceAll("\\(", "（");
            String method = "";
            if (methodName.contains("(")) {
                method = methodName.substring(0, methodName.indexOf("("));
            }
            else if (methodName.contains("（")) {
                method = methodName.substring(0, methodName.indexOf("（"));
            }
            else {
                exception.add("接口格式不对:" + methodName);
                continue;
            }
            String bizkeys = "";
            try {
                bizkeys = getBizkey(method);
            }
            catch (Exception e) {
                exception.add(e.getMessage());
                continue;
            }
            if (bizkeys.startsWith("|")) {
                bizkeys = bizkeys.substring(1);
            }
            System.out.println(method + ":" + bizkeys);
            sql += "INSERT INTO TF_B_METHOD_BIZKEY (METHOD,METHOD_NAME,BIZKEY) VALUES ('" + method + "','" + methodName
                    + "','" + bizkeys + "');";
        }
        System.out.println("异常信息:" + exception);
        System.out.println("入库sql:" + sql);
    }

    /**
     * 根据method获取其对应的bizkey
     * @param method
     * @return
     * @throws Exception
     */
    public static List<String> getBizkeyByMethod(String method) throws Exception {
        List<String> bizkeys = new ArrayList<String>();
        bizkeys.add("CS-012");
        return bizkeys;
    }

    /**
     * 根据method获取对应的bizkey
     * @param method
     * @return
     * @throws Exception
     */
    private static String getBizkey(String method) throws Exception {
        if (TestUtils.isEmpty(bizkeys) && !TestUtils.isEmpty(exception)) {
            throw new Exception(exception);
        }
        String bizs = "";
        for (Bizkey bizkey : bizkeys) {
            List<Method> methodList = bizkey.getAllowMethods();
            for (Method bizMethod : methodList) {
                if (method.equals(bizMethod.getMethod())) {
                    bizs += "|" + bizkey.getBizkey();
                }
            }
        }
        if (TestUtils.isEmpty(bizs)) {
            throw new Exception("根据method:" + method + " 未获取到对应的bizkey,请检查");
        }
        return bizs;
    }

    /**
     * 1,获取最新的bizkey关系文件路径
     * @return
     * @throws Exception
     */
    private static String getBizkeyExcelPath(String bizkeyExcel) throws Exception {
        File file = new File(bizkeyExcel);
        File[] files = null;
        if (file.isDirectory()) {
            files = file.listFiles();
        }
        if (null == files) {
            return "";
        }
        String lastFileName = "19930315";
        String fileName = "业务流程梳理关系.xlsx";
        for (File tempFile : files) {
            if (tempFile.getName().indexOf("-") < 0) {
                continue;
            }
            String FileTime = tempFile.getName().substring(tempFile.getName().indexOf("-") + 1,
                    tempFile.getName().indexOf(".xlsx"));
            if (lastFileName.compareTo(FileTime) < 0) {
                fileName = tempFile.getName();
            }
        }
        return TestUtils.bizKeyExcel + fileName;
    }

    /**
     * 2,获取到所有的bizkey
     * @param bizkeyPath-业务流程梳理关系路径
     * @return
     * @throws Exception
     */
    private static List<Bizkey> getAllBizkey(String bizkeyPath) throws Exception {
        XSSFWorkbook work = new XSSFWorkbook(new FileInputStream(bizkeyPath));
        Sheet sheet = work.getSheetAt(0);
        List<Bizkey> bizkeys = new ArrayList<Bizkey>();
        Bizkey bizkey = null;

        String lastBizkey = "begin";
        int rowNum = -1;

        for (Row row : sheet) {
            try {
                if (TestUtils.isEmpty(row)) {
                    continue;
                }
                rowNum = row.getRowNum();
                if (rowNum == 0) { // 第一行为标题栏,不读取
                    continue;
                }
                String biz = getCellString(row.getCell(1));
                if (!TestUtils.isEmpty(biz) && !biz.equals(lastBizkey)) {// 如果是回一个新的bizkey则要获取其固定的值
                    if (!TestUtils.isEmpty(bizkey)) {// 将上一个bizkey的实例放入集合中
                        bizkeys.add(bizkey);
                    }
                    // 开始放新的bizkey
                    bizkey = new Bizkey();
                    bizkey.setBizkey(biz);
                    bizkey.setBizName(getCellString(row.getCell(2)));
                    bizkey.setExplain(getCellString(row.getCell(3)));
                    // bizkey.setAllowMethodCodes(Config.getStr("ecaop.core.biz." + bizkey.getBizkey() + ".def"));
                    // 新的方式,只获取bizkey下面的method短名来判断接口所属的bizkey
                    lastBizkey = biz;
                }
                // 获取这一行的method参数,放到bizkey的method成员变量中
                Method method = new Method();
                method.setMethod(getCellString(row.getCell(4)));
                if (TestUtils.isEmpty(method.getMethod())) {// 空行略过
                    continue;
                }
                method.setMethodName(getCellString(row.getCell(5)));
                // method.setMethodCode(Config.getStr("ecaop.core.method.map." + method.getMethod()));
                List<Method> methods = null;
                if (TestUtils.isEmpty(bizkey.getAllowMethods())) {
                    methods = new ArrayList<Method>();
                }
                else {
                    methods = bizkey.getAllowMethods();
                }
                methods.add(method);
                bizkey.setAllowMethods(methods);
            }
            catch (Exception e) {
                if (e.getMessage().contains("END")) {
                    bizkeys.add(bizkey);
                }
                else {
                    System.out.println(bizkeys);
                    throw new Exception("第" + (rowNum + 1) + "中有" + e.getMessage());
                }
            }
        }
        // System.out.println(bizkeys);
        return bizkeys;
    }

    /**
     * 获取格子中的内容
     * @param cell
     * @return
     * @throws Exception
     */
    private static String getCellString(Cell cell) throws Exception {
        if (TestUtils.isEmpty(cell)) {// 如果cell为空证明已读取结束
            throw new Exception("END");
        }
        cell.setCellType(Cell.CELL_TYPE_STRING);
        return cell.getStringCellValue();
    }

}
